/**
 *   sci4j - Java library for scientific computation.
 *
 *   Copyright (C) 2010 Inaki Ortiz de Landaluce
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package org.sci4j.imaging.utils;

public class ByteUtils {

	/**
	 * Converts Big Endian byte-ordered bytes to a 4-byte integer
	 * @param b multiple byte binary array	  
	 * @param offset offset value
	 * @return the integer value corresponding to a 32-bit representation
	 */
	public static int bytesBE2int(byte[] b, int off) {
		return (((b[off] & 0xff) << 24) | ((b[off + 1] & 0xff) << 16)
				| ((b[off + 2] & 0xff) << 8) | (b[off + 3] & 0xff));
	}
	
	/**
	 * Converts Little Endian byte-ordered bytes to a 4-bytes integer
	 * @param b multiple byte binary array	  
	 * @param offset offset value
	 * @return the integer value corresponding to a 32-bit representation
	 */
	public static int bytesLE2int(byte[] b, int off) {
		return ((b[off] & 0xff) | ((b[off + 1] & 0xff) << 8)
				| ((b[off + 2] & 0xff) << 16) | ((b[off + 3] & 0xff) << 24));
	}
	
	/**
	 * Converts Big Endian byte-ordered bytes to a 8-bytes float
	 * @param b multiple byte binary array	  
	 * @param offset offset value
	 * @return the float value corresponding to a 64-bit representation 
	 */
	public static float bytesBE2float(byte[] b, int off) {
		return (((b[off] & 0xff) << 56) | ((b[off + 1] & 0xff) << 48)
				| ((b[off + 2] & 0xff) << 40) | ((b[off + 3] & 0xff) << 32)
				| ((b[off + 4] & 0xff) << 24) | ((b[off + 5] & 0xff) << 16)
				| ((b[off + 6] & 0xff) << 8)  | (b[off + 7] & 0xff));
	}
	
	/**
	 * Converts Little Endian byte-ordered bytes to a 8-bytes float
	 * @param b multiple byte binary array	  
	 * @param offset offset value
	 * @return the float value corresponding to a 64-bit representation
	 */
	public static float bytesLE2float(byte[] b, int off) {
		return ((b[off] & 0xff) | ((b[off + 1] & 0xff) << 8)
				| ((b[off + 2] & 0xff) << 16) | ((b[off + 3] & 0xff) << 24));
	}
	
	
}
